<?php
namespace app\common\controller;

use think\facade\Config;
class Encrypt{
    protected static $key = '';
    /**
     * Encrypt constructor.
     */
    public function __construct(){
        self::$key = Config::get('app.encode');
    }

    /**
     * @param string $string
     * @param string $skey
     * @return mixed
     */
    public static function  encode($string = '', $skey = '') {
        $self = new self();
        $skey = $skey?$skey:$self::$key;
        $strArr = str_split(base64_encode($string));
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key < $strCount && $strArr[$key].=$value;
        return str_replace([
            '=',
            '+',
            '/'
        ],[
            'O0O0O',
            'o000o',
            'oo00o'
        ], join('', $strArr));
    }

    /**
     * @param string $string
     * @param string $skey
     * @return bool|string
     */
    public static function decode($string = '', $skey = '') {
        $self = new self();
        $skey = $skey?$skey:$self::$key;
        $strArr = str_split(str_replace([
            'O0O0O',
            'o000o',
            'oo00o'
        ],[
            '=',
            '+',
            '/'
        ],$string), 2);
        $strCount = count($strArr);
        foreach (str_split($skey) as $key => $value)
            $key <= $strCount  && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
        return base64_decode(join('', $strArr));
    }
}